package com.changgou.seckill.controller;

import com.changgou.core.controller.AbstractCoreController;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.seckill.config.TokenDecode;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.pojo.SeckillStatus;
import com.changgou.seckill.service.SeckillOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author liyipeng
 * @date 2021-06-26 17:00
 */
@RestController
@RequestMapping("/seckill/order")
@CrossOrigin
public class SeckillOrderController extends AbstractCoreController<SeckillOrder> {

    private SeckillOrderService seckillOrderService;

    @Autowired
    public SeckillOrderController(SeckillOrderService seckillOrderService) {
        super(seckillOrderService, SeckillOrder.class);
        this.seckillOrderService = seckillOrderService;
    }


    @Autowired
    private TokenDecode tokenDecode;

    /****
     * URL:/seckill/order/add
     * 添加订单
     * 调用Service增加订单
     * 匿名访问：anonymousUser
     * @param time
     * @param id
     */
    @RequestMapping(value = "/add")
    public Result add(String time, Long id) {
        try {
            //用户登录名
//            String username = tokenDecode.getUsername();
            //TODO
            String username = "zhangsan";

            Boolean bo = seckillOrderService.add(id, time, username);

            if (bo) {
                //抢单成功
                return new Result(true, StatusCode.OK, "抢单成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, e.getMessage());
        }
        return new Result(false, StatusCode.ERROR, "服务器繁忙，请稍后再试");
    }

    /**
     * 查询抢购
     * @return
     */
    @GetMapping("/query")
    public Result<SeckillStatus> queryStatus(){
        //TODO 用户名
        String username="zhangsan";
        SeckillStatus seckillStatus= seckillOrderService.queryStatus(username);
        //秒杀的订单
        if(seckillStatus!=null) {
            seckillStatus.setType(2);
        }
        return new Result<SeckillStatus>(true,StatusCode.OK,"查询状态成功",seckillStatus);
    }

}
